﻿using com.nm;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.library.Helper;
using NHibernateVertica;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.library;
using Vertica.Data.VerticaClient;
using VerticaAPI.model;
using static VerticaAPI.model.DwCZPJudgePeriodModel;

namespace VerticaAPI
{
    [Description("爆畅滞平区间设置")]
    public class DwCZPJudgePeriodHandler : BaseHandler
    {
        public VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();

        #region 没SQL不用改版

        #region 生命周期区间设置列表 GetLifeCycleList

        [MustLogin]
        [Description("生命周期区间设置列表")]
        [ReturnType(typeof(IList<LifeCycleInfo>))]
        public ApiResult GetLifeCycleList([ParamDescription("生命周期(天)")] string dayNum)
        {
            if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
            {
                return Error("该用户不属于任何公司!");
            }
            if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
            {
                return Error("该用户所在公司没有任何数据源!");
            }

            if (string.IsNullOrWhiteSpace(dayNum)) { return Error("【生命周期(天)】参数不能为空！"); };
            var dt = LifeCycleList(dayNum);
            var query = ModelConvertHelper<LifeCycleInfo>.ConvertToModel(dt).ToList();
            var result = query.Select(t => new LifeCycleInfo()
            {
                LifeDays = t.LifeDays,
                PeriodName = t.PeriodName,
                BeginDay = t.BeginDay,
                EndDay = t.EndDay,
                CZPJudgePeriodList = ModelConvertHelper<CZPJudgePeriod>.ConvertToModel(PeriodList(t.LifeDays, t.PeriodName)).ToList()
            }).ToList();
            return Success(result);
        }

        #endregion

        #region 爆畅滞平区间设置列表 GetCZPJudgePeriodList

        [MustLogin]
        [Description("爆畅滞平区间设置列表")]
        [ReturnType(typeof(IList<CZPJudgePeriod>))]
        public ApiResult GetCZPJudgePeriodList(
            [ParamDescription("生命周期(天)")] int dayNum,
            [ParamDescription("区间名称")] string periodName)
        {
            if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
            {
                return Error("该用户不属于任何公司!");
            }
            if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
            {
                return Error("该用户所在公司没有任何数据源!");
            }

            if (string.IsNullOrWhiteSpace(periodName))
            {
                return Error("【区间名称】参数不能为空！");
            }
            ;
            var dt = PeriodList(dayNum, periodName);
            var query = ModelConvertHelper<CZPJudgePeriod>.ConvertToModel(dt).ToList();
            var result = query.Select(t => new CZPJudgePeriod()
            {
                SaleFlag = t.SaleFlag,
                BeginValue = t.BeginValue,
                EndValue = t.EndValue
            }).ToList();
            return Success(result);
        }

        #endregion

        #endregion

        #region (ok)修改生命周期区间 ModifyLifeCycle

        [JsonType]
        [MustLogin]
        [Description("修改生命周期区间")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult ModifyLifeCycle([ParamDescription("生命周期区间")] ModifyLifeCycle param)
        {
            if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
            {
                return Error("该用户不属于任何公司!");
            }
            if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
            {
                return Error("该用户所在公司没有任何数据源!");
            }

            if (param == null) { return Error("【生命周期区间】参数不能为空！"); };
            if (string.IsNullOrWhiteSpace(param.LifeDays)) { return Error("【生命周期(天)】参数不能为空！"); };
            try
            {
                var cmdList = new List<CommandInfo>()
                {
                    new CommandInfo()
                    {
                        CommandText = $"DELETE FROM  ndw.ndw_CZPJudgePeriod WHERE  CompanyID = '{UserInfo.UserCompanyId}' and  lifedays = {param.LifeDays} "
                    }
                };
                foreach (var item in param.LifeCycleInfo)
                {
                    foreach (var subItem in item.CZPJudgePeriodList)
                    {
                        var insertParams = new VerticaParameter[]
                                {
                            new VerticaParameter("@ExtrSource", UserInfo.UserExtrSource),
                            new VerticaParameter("@CompanyID", UserInfo.UserCompanyId),
                            new VerticaParameter("@LifeDays", param.LifeDays),
                            new VerticaParameter("@PeriodName", item.PeriodName),
                            new VerticaParameter("@BeginDay", item.BeginDay),
                            new VerticaParameter("@EndDay", item.EndDay),
                            new VerticaParameter("@SaleFlag", subItem.SaleFlag),
                            new VerticaParameter("@Beginvalue", subItem.BeginValue),
                            new VerticaParameter("@Endvalue", subItem.EndValue),
                            new VerticaParameter("@BeginCalc", Convert.ToDouble((Convert.ToDouble(subItem.BeginValue)/100/Convert.ToDouble(item.EndDay)).ToString("0.0000"))),
                            new VerticaParameter("@EndCalc", Convert.ToDouble(((subItem.EndValue == 0 ? 1 : Convert.ToDouble(subItem.EndValue)/100/Convert.ToDouble(item.EndDay))).ToString("0.0000"))),
                            new VerticaParameter("@sortId", subItem.SortId)
                                };
                        var insertCmd = new CommandInfo()
                        {
                            CommandText = @"insert into ndw.ndw_CZPJudgePeriod(ExtrSource,CompanyID,LifeDays,PeriodName,BeginDay,EndDay,SaleFlag,Beginvalue,Endvalue,BeginCalc,EndCalc,sortId)
                                           values(@ExtrSource,@CompanyID,@LifeDays,@PeriodName,@BeginDay,@EndDay,@SaleFlag,@Beginvalue,@Endvalue,@BeginCalc,@EndCalc,@sortId)",
                            Parameters = insertParams
                        };
                        cmdList.Add(insertCmd);
                    }
                }
                //执行
                Log.WriteLog(cmdList.ToString());
                Helper.ExecuteSqlTran(cmdList);
                return Success(0);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        #endregion

        #region (ok)获取数据列表 LifeCycleList

        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <param name="dayNum"></param>
        /// <returns></returns>
        public DataTable LifeCycleList(string dayNum)
        {
            try
            {
                var sql = $"select distinct LifeDays,PeriodName,BeginDay,EndDay from ndw.ndw_CZPJudgePeriod " +
                          $"where  CompanyID = '{UserInfo.UserCompanyId}' and  lifedays = {dayNum} order by BeginDay ";
                var cmd = Helper.GetSqlStringCommand(sql);
                return Helper.ExecuteDataTable(cmd);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        #endregion

        #region (ok)PeriodList PeriodList

        public DataTable PeriodList(int dayNum, string periodName)
        {
            try
            {
                var sql = $"select * from ndw.ndw_CZPJudgePeriod " +
                          $"where  CompanyID = '{UserInfo.UserCompanyId}' and  lifedays = {dayNum} and periodName = '{periodName}' order by sortId";
                var cmd = Helper.GetSqlStringCommand(sql);
                return Helper.ExecuteDataTable(cmd);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        #endregion

        #region (ok)获取爆畅滞平数据(首页图表专用) GetSizetypeCount(ok)

        [MustLogin]
        [Description("获取爆畅滞平数据(首页图表专用)")]
        [ReturnType(typeof(IList<DwCZPJudgePeriodModel.ChartModel>))]
        public ApiResult GetSizetypeCount()
        {
            if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
            {
                return Error("该用户不属于任何公司!");
            }
            if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
            {
                return Error("该用户所在公司没有任何数据源!");
            }

            //只查上一天的
            var date = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            var sql = $"select count(skcczpflag) ,skcczpflag as 'BCZPTypeName'  " +
                      $"from ndw.ndw_SuppleAllMessage " +
                      $"where CompanyID = '{UserInfo.UserCompanyId}' " +
                      $"group by skcczpflag,stockdate,yearno " +
                      $"having stockdate='{date}' and yearno='{DateTime.Now.Year}' " +
                      $"limit 100 ";
            var cmd = Helper.GetSqlStringCommand(sql);
            var dt = Helper.ExecuteDataTable(cmd);
            var list = ModelConvertHelper<ChartModel>.ConvertToModel(dt).OrderBy(d => d.Count);
            return Success(list);
        }
        #endregion
       
    }
}
